package com.oneday.ashop.console.authority;

import com.oneday.ashop.console.base.shiro.MyRealm;
import com.oneday.ashop.console.base.shiro.filter.BaseResourceFilter;
import com.oneday.ashop.console.base.support.BaseServiceSupport;
import com.oneday.ashop.console.resource.ResourceDao;
import com.oneday.ashop.core.base.util.CollectionUtil;
import com.oneday.ashop.core.entity.Admin;
import com.oneday.ashop.core.entity.Page;
import com.oneday.ashop.core.entity.Resource;
import com.oneday.ashop.core.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 *  权限管理服务层
 * Created by admin on 2016/7/3.
 */
@Service
public class AuthService extends BaseServiceSupport {

    @Autowired
    private AuthDao authDao;

    @Autowired
    private BaseResourceFilter baseResourceFilter;

    @Autowired
    private MyRealm myRealm;


//    @PostConstruct
    public void init() {
        baseResourceFilter.init();
    }

    /**
     * 添加资源
     * @param resource
     */
    public void addResource(Resource resource) {
        resource.setCreateTime(new Date());
        resource.setAdminId(getCurrentAdmin().getId());
        resource.setAdminName(getCurrentAdmin().getName());
        authDao.addResource(resource);
        //刷新资源过滤器中的缓存
        baseResourceFilter.init();
    }

    /**
     * 删除资源
     * @param resourceId
     */
    public void deleteResource(Integer resourceId) {
        Update update = Update.update("status", Resource.STATUS_DELETE).set("lastModifyTime", new Date());
        authDao.findAndModifyResource(resourceId, update);
    }

    /**
     * 获得所有的资源
     * @return
     */
    public List<Resource> getALlResources() {
        return authDao.findAllResources();
    }

    /**
     * 角色管理
     * @return
     */
    public List<Role> roleManager() {
        return authDao.findALlRoles();
    }

    /**
     * 添加角色
     * @param role
     */
    public void roleAdd(Role role) {
        role.setCreateTime(new Date());
        role.setAdminId(getCurrentAdmin().getId());
        role.setAdminName(getCurrentAdmin().getName());
        authDao.addRole(role);
    }

    /**
     * 获得菜单
     * @return
     */
    public List<Resource> getMenu() {
        List<Resource> resources = authDao.findAllResources();
        //一级资源的集合
        Map<Integer, Resource> resourceMap = new HashMap<>();
        //二级资源的集合
        Map<Integer, List<Resource>> secondResourceMap = new HashMap<>();
        for(Resource resource : resources) {
            if(resource.getLevel() == 1) {
                resourceMap.put(resource.getId(), resource);
            }else {
                if(secondResourceMap.containsKey(resource.getParentId())) {
                    secondResourceMap.get(resource.getParentId()).add(resource);
                }else {
                    List<Resource> tempResource = new ArrayList<>();
                    tempResource.add(resource);
                    secondResourceMap.put(resource.getParentId(), tempResource);
                }
            }
        }
        //遍历一级资源
        List<Resource> result = new ArrayList<>();
        for(Integer key : resourceMap.keySet()) {
            resourceMap.get(key).setChildRes(secondResourceMap.get(key));
            result.add(resourceMap.get(key));
        }
        return result;
    }
    /**
     * 修改角色资源
     * @param roleId
     * @param resourceIds
     */
    public void modifyResourceOfRole(Integer roleId, String resourceIds) {
        Set<Integer> resourceIdsSet= new TreeSet<>();
        //去重，去掉不合法的资源id
        for(String str : resourceIds.split(",")) {
            Integer resourceId = Integer.parseInt(str);
            if (resourceId < 0) {
                continue;
            }
            resourceIdsSet.add(Integer.parseInt(str));
        }
        Update update = Update.update("resources", resourceIdsSet);
        authDao.updateRole(roleId, update);
        //清除所有用户的授权信息
        myRealm.clearAllCachedAuthorizationInfo();
    }

    /**
     * 获得所有的角色
     * @return
     */
    public List<Role> getAllRoles() {
         return  authDao.findRoles();
    }

    /**
     * 获得用户的拥有的角色
     * @param adminId
     * @return
     */
    public List<Role> getAdminRoles(Integer adminId) {
        Admin admin = authDao.findAdminById(adminId);
        List<Role> roles =  authDao.findRoles();
        for(Role role : roles) {
            if(admin.getRoleIds() != null && admin.getRoleIds().contains(role.getId())) {
                role.setChecked(true);
            }
        }
        return roles;
    }
    /**
     * 获得Ztree的资源
     * @return
     */
    public Object[] getZTreeResource(Integer roleId) {
        //查询该角色拥有的资源
        List<Integer> hadResources = authDao.findRoleById(roleId, "resources").getResources();

        List<Resource> resources = getALlResources();
        Map<Integer, Resource> resourceMap = CollectionUtil.buildMap(resources, Integer.class, Resource.class, "id");
        //按资源类型分类
        List<Resource> pageResources = new ArrayList<>();
        List<Resource> buttonResources = new ArrayList<>();
        List<Resource> jsonResources = new ArrayList<>();
        for(Resource resource : resources) {
            //判断该角色是否拥有该资源
            if(hadResources != null && hadResources.contains(resource.getId())) {
                resource.setChecked(true);
            }
            if(Resource.TYPE_PAGE.equals(resource.getType())) {
                pageResources.add(resource);
            }else if(Resource.TYPE_BUTTON.equals(resource.getType())) {
                buttonResources.add(resource);
            }else if(Resource.TYPE_JSON.equals(resource.getType())) {
                jsonResources.add(resource);
            }
        }
        //给button资源增加上级资源
        List<Integer> parentIds = CollectionUtil.buildList(buttonResources, Integer.class, "parentId");
        for(Integer id : parentIds) {
            buttonResources.add(resourceMap.get(id));
        }
        return new Object[]{pageResources, buttonResources, jsonResources};
    }

    /**
     * 管理员的分页数据
     * @param page 分页实体
     */
    public void adminManager(Page<Admin> page) {
        authDao.findAdminPage(page);
        List<Role> roles = getAllRoles();
        Map<Integer, Role> roleMap = CollectionUtil.buildMap(roles, Integer.class, Role.class, "id");
        for(Admin admin : page.getResult()) {
            List<Integer> roleIds = admin.getRoleIds();
            if(roleIds == null) {
                continue;
            }
            List<String> roleNames = new ArrayList<>();
            for(Integer id : roleIds) {
                roleNames.add(roleMap.get(id).getName());
            }
            admin.setRoleNames(roleNames);
        }
    }

    /**
     * 添加管理员
     * @param admin
     */
    public void addAdmin(Admin admin) {
        admin.setAdminId(getCurrentAdmin().getId());
        admin.setAdminName(getCurrentAdmin().getName());
        admin.setCreateTime(new Date());
        authDao.addAdmin(admin);
    }

    /**
     * 为用户分配角色
     * @param adminId
     * @param roleIds
     */
    public void assignRoles(Integer adminId, List<Integer> roleIds) {
        Update update = Update.update("roleIds", roleIds);
        authDao.updateAdmin(adminId, update);
        //清除所有的授权的缓存信息
        myRealm.clearAllCachedAuthorizationInfo();

    }

    /**
     * 根据角色id查找角色
     * @param roleIds
     */
    public List findRoles(List<Integer> roleIds) {
        return authDao.findRoles(roleIds);
    }
}
